import React, { useEffect, useRef, useState } from 'react';
import { Box, DatePicker2 } from '@alifd/next';
import { useStore } from '@/hooks';
import { observer } from 'mobx-react-lite';
import { t } from '@lingui/macro';
import dayjs from 'dayjs';
import moment from 'moment';
import styles from './PieGroup.module.scss';

import PieChart from './PieChart';

const RangePreset = {};
RangePreset[t`昨日`] = [dayjs().subtract(1, 'day'), dayjs()];
RangePreset[t`近一周`] = [dayjs().add(-7, 'day'), dayjs()];
RangePreset[t`近二周`] = [dayjs().add(-15, 'day'), dayjs()];

const _barWidth = '10%';

function SubGroupInfo() {
  const { dashboardStore: store, ruleStore } = useStore();
  const [date, setDate] = useState([moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]);
  const [state, setState] = useState({});

  useEffect(() => {
    const [start, end] = date;
    const from = start || moment().format('YYYY-MM-DD');
    const to = end || moment().format('YYYY-MM-DD');
    (async () => {
      const fetchOrderCount = async (sortKey) => {
        return await store.orderCount({
          search: { groupIds: [ruleStore._group_id], from, to },
          pg: { size: 10, page: 0, sort: [sortKey] },
        });
      };

      const topLeft = await fetchOrderCount('issueOrderCount;desc');
      const topRight = await fetchOrderCount('takeOrderCount;desc');
      const bottomLeft = await fetchOrderCount('issueOrderTotalCount;desc');
      const bottomRight = await fetchOrderCount('takeOrderTotalCount;desc');

      const orderTotal = await store.orderTotal({
        search: { groupIds: [ruleStore._group_id], from, to },
      });

      const { issueOrderTotalCount, takeOrderTotalCount, issueOrderCount, takeOrderCount } = orderTotal;

      const createTempData = (data, valueKey) =>
        data.map((p, i) => ({
          name: `${i + 1}: ${p.nickname}`,
          value: p[valueKey],
        }));

      const tempTopLeft = createTempData(topLeft, 'issueOrderCount');
      const tempTopRight = createTempData(topRight, 'takeOrderCount');
      const tempBottomLeft = createTempData(bottomLeft, 'issueOrderTotalCount');
      const tempBottomRight = createTempData(bottomRight, 'takeOrderTotalCount');

      const calculateTotal = (data) => data.reduce((acc, arr) => acc + arr.value, 0);

      const topLeftTotal = calculateTotal(tempTopLeft);
      const topRightTotal = calculateTotal(tempTopRight);
      const tempBottomLeftTotal = calculateTotal(tempBottomLeft);
      const tempBottomRightTotal = calculateTotal(tempBottomRight);

      const addOthers = (data, total, originalCount) =>
        data.push({ name: '其他', value: originalCount - total, total: originalCount });

      addOthers(tempTopLeft, topLeftTotal, issueOrderCount);
      addOthers(tempTopRight, topRightTotal, takeOrderCount);
      addOthers(tempBottomLeft, tempBottomLeftTotal, issueOrderTotalCount);
      addOthers(tempBottomRight, tempBottomRightTotal, takeOrderTotalCount);

      setState({
        topLeft: tempTopLeft,
        topRight: tempTopRight,
        bottomLeft: tempBottomLeft,
        bottomRight: tempBottomRight,
      });
    })();
  }, [date, ruleStore._group_id]);

  /**
   * 选择时间范围事件
   * @param {*} e
   * @param {*} v
   */
  const handleOnDate = (e, v) => {
    setDate(v);
  };

  return (
    <>
      <div className={styles.borderTop} />
      <div style={{ padding: 20 }}>
        <Box direction="row" align="center" wrap={!!ruleStore._isPhone}>
          <div className={styles.title}>{t`出单/接单单日前十:`}</div>
          <DatePicker2.RangePicker
            style={{ width: 100, marginLeft: ruleStore._isPhone ? 0 : 20 }}
            onChange={handleOnDate}
            preset={RangePreset}
            value={date}
          />
        </Box>
        <Box direction="row" wrap={!!ruleStore._isPhone} style={{ margin: '10px 0' }}>
          <PieChart title={t`出单量前十`} data={state?.topLeft} />
          <PieChart title={t`接单量前十`} data={state?.topRight} />
        </Box>
      </div>
      <div className={styles.borderTop} />
      <div style={{ padding: 20 }}>
        <Box direction="row" align="center" >
          <div className={styles.title}>{t`出单/接单总量前十:`}</div>
        </Box>
        <Box direction="row" wrap={!!ruleStore._isPhone}>
          <PieChart title={t`出单总量前十`} data={state?.bottomLeft} />
          <PieChart title={t`接单总量前十`} data={state?.bottomRight} />
        </Box>
      </div>
    </>
  );
}

export default observer(SubGroupInfo);
